<template>
  <div class="history-list-container">
    <!-- 页面标题与操作按钮 -->
    <div class="page-header">
      <!-- <h1 class="page-title">
        <i class="fa fa-history text-primary mr-2"></i>
        评分历史记录
      </h1> -->
      <div class="header-actions">
        <el-button
          type="default"
          :icon="Refresh"
          @click="handleRefresh"
          size="small"
        >
          刷新
        </el-button>
        <el-button
          type="default"
          :icon="Download"
          @click="handleExport"
          size="small"
        >
          导出Excel
        </el-button>
        <!-- <el-button
          type="primary"
          :icon="Filter"
          @click="showAdvancedFilter = !showAdvancedFilter"
          size="small"
        >
          高级筛选
        </el-button> -->
      </div>
    </div>

    <!-- 统计卡片区 -->
    <StatisticsCards :statistics="statistics" :loading="statsLoading" />

    <!-- 筛选区 -->
    <FilterPanel
      ref="filterPanelRef"
      :show-advanced="showAdvancedFilter"
      @search="handleSearch"
    />

    <!-- 历史记录表格 -->
    <HistoryTable
      :columns="tableColumns"
      :data="historyList"
      :loading="tableLoading"
      :pagination="pagination"
      @current-page-change="handlePageChange"
      @size-change="handleSizeChange"
      @view-detail="handleViewDetail"
      @compare="handleCompare"
    />

    <!-- 历史趋势图 -->
    <!-- <HistoryChart :chart-data="chartData" :loading="chartLoading" /> -->

    <!-- 历史详情对话框 -->
    <HistoryDetailDialog
      v-model="showDetailDialog"
      :detail-id="currentDetailId"
      @close="showDetailDialog = false"
    />

    <!-- 评分对比对话框 -->
    <ScoreCompareDialog
      v-model="showCompareDialog"
      :asset-ip="currentCompareIp"
      :initial-ids="currentCompareIds"
      @close="showCompareDialog = false"
    />

    <!-- 高级筛选对话框 -->
    <el-dialog
      v-model="showAdvancedFilterDialog"
      title="高级筛选"
      width="600px"
      destroy-on-close
    >
      <AdvancedFilterForm
        :form-data="advancedFilterForm"
        @confirm="handleAdvancedFilterConfirm"
        @reset="handleAdvancedFilterReset"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch, h } from "vue";
import { TableColumn, PaginationConfig } from "@/components/DynamicTable/types";
import { ElMessage, ElMessageBox, ElTag, ElButton } from "element-plus";
import { Refresh, Download, Filter } from "@element-plus/icons-vue";

// 组件导入
import StatisticsCards from "./components/StatisticsCards.vue";
import FilterPanel from "./components/FilterPanel.vue";
import HistoryTable from "./components/HistoryTable.vue";
// import HistoryChart from "./components/HistoryChart.vue";
import HistoryDetailDialog from "./components/HistoryDetailDialog.vue";
import ScoreCompareDialog from "./components/ScoreCompareDialog.vue";
import AdvancedFilterForm from "./components/AdvancedFilterForm.vue";

// API导入
import {
  getHistoryList,
  getHistoryStatistics,
  getHistoryChartData,
  exportHistoryData,
} from "../../servers";

// 表格列配置
const tableColumns = ref<TableColumn[]>([
  // {
  //   label: "序号",
  //   prop: "index",
  //   width: 60,
  //   show: true,
  //   render: (row, index) => h("span", { class: "text-center" }, index + 1),
  // },
  {
    label: "评分时间",
    prop: "calculated_at",
    show: true,
  },
  {
    label: "资产IP",
    prop: "asset_ip",
    show: true,
    render: (row) => {
      return h("span", { class: "monospace-text" }, row.asset_ip);
    },
  },
  {
    label: "总分",
    prop: "total_score",
    show: true,
    render: (row) => {
      return h(
        "span",
        { class: getScoreClass(row.total_score) },
        row.total_score
      );
    },
  },
  {
    label: "风险等级",
    prop: "risk_level",
    show: true,
    render: (row) => {
      return h("div", { class: "flex items-center" }, [
        h("span", {
          class: `risk-indicator ${getRiskClass(row.risk_level)}`,
        }),
        h("span", getRiskText(row.risk_level)),
      ]);
    },
  },
  {
    label: "变更类型",
    prop: "change_type_desc",
    width: 120,
    show: true,
    render: (row) => {
      const isAuto =
        row.change_type === "auto_calculation" ||
        row.change_type_desc === "自动计算";
      return h(
        ElTag,
        {
          type: isAuto ? "info" : "warning",
          size: "small",
        },
        row.change_type_desc || row.change_type
      );
    },
  },
  {
    label: "操作",
    prop: "action",
    width: 140,
    show: true,
    render: (row) => {
      return h("div", { class: "flex" }, [
        h(
          ElButton,
          {
            size: "small",
            onClick: () => handleViewDetail(row.id),
          },
          {
            default: () => "详情",
          }
        ),
        h(
          ElButton,
          {
            size: "small",
            onClick: () => handleCompare(row),
          },
          {
            default: () => "对比",
          }
        ),
      ]);
    },
  },
]);

// 分页配置
const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50, 100],
  layout: "total, sizes, prev, pager, next",
  background: true,
});

// 响应式数据
const statistics = ref({
  total_records: 0,
  today_records: 0,
  week_records: 0,
  avg_score_change: 0,
  abnormal_records: 0,
});

const historyList = ref([]);
const chartData = ref(null);
const filterForm = ref({
  time_range: "7d",
  asset_ip: "",
  risk_level: "",
  change_type: "",
  score_min: 60,
  score_max: 100,
  department: "",
  template: "default_v1",
  sort_by: "score_time",
  sort_order: "desc",
});

const advancedFilterForm = ref({
  start_date: "",
  end_date: "",
  asset_group: "",
  operator: "",
  has_change: "",
  dimension: "",
});

// 状态控制
const statsLoading = ref(false);
const tableLoading = ref(false);
const chartLoading = ref(false);
const showAdvancedFilter = ref(false);
const showAdvancedFilterDialog = ref(false);
const showDetailDialog = ref(false);
const showCompareDialog = ref(false);
const currentDetailId = ref("");
const currentCompareIp = ref("");
const currentCompareIds = ref([]);
const filterPanelRef = ref(null);

// 辅助函数 - 风险等级样式和文本
const getRiskClass = (level) => {
  const classMap = {
    low: "bg-success",
    medium: "bg-warning",
    high: "bg-orange-500",
    critical: "bg-danger",
  };
  return classMap[level] || "bg-gray-400";
};

const getRiskText = (level) => {
  const textMap = {
    low: "低",
    medium: "中等",
    high: "高",
    critical: "严重",
  };
  return textMap[level] || level;
};

// 辅助函数 - 分数样式
const getScoreClass = (score) => {
  if (score >= 80) return "text-success font-medium";
  if (score >= 60) return "text-warning font-medium";
  return "text-danger font-medium";
};

// 辅助函数 - 转换时间范围为日期范围
const convertTimeRange = (timeRange: string) => {
  const today = new Date();
  today.setHours(23, 59, 59, 999);
  const endDate = new Date(today);
  let startDate = new Date(today);

  switch (timeRange) {
    case "today":
      startDate.setHours(0, 0, 0, 0);
      break;
    case "7d":
      startDate.setDate(today.getDate() - 6);
      startDate.setHours(0, 0, 0, 0);
      break;
    case "30d":
      startDate.setDate(today.getDate() - 29);
      startDate.setHours(0, 0, 0, 0);
      break;
    case "month":
      startDate = new Date(today.getFullYear(), today.getMonth(), 1);
      startDate.setHours(0, 0, 0, 0);
      break;
    case "lastmonth":
      startDate = new Date(today.getFullYear(), today.getMonth() - 1, 1);
      startDate.setHours(0, 0, 0, 0);
      endDate.setDate(0);
      endDate.setHours(23, 59, 59, 999);
      break;
    default:
      // 默认返回最近7天
      startDate.setDate(today.getDate() - 6);
      startDate.setHours(0, 0, 0, 0);
  }

  const formatDate = (date: Date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    return `${year}-${month}-${day}`;
  };

  return {
    start_date: formatDate(startDate),
    end_date: formatDate(endDate),
  };
};

// 辅助函数 - 转换变更类型
const convertChangeType = (changeType: string) => {
  const typeMap: Record<string, string> = {
    自动计算: "auto_calculation",
    人工调整: "manual_edit",
  };
  return typeMap[changeType] || changeType;
};

// 辅助函数 - 转换排序字段
const convertSortField = (sortBy: string) => {
  const fieldMap: Record<string, string> = {
    score_time: "calculated_at",
    total_score: "total_score",
    risk_level: "risk_level",
  };
  return (fieldMap[sortBy] || "calculated_at") as
    | "calculated_at"
    | "total_score"
    | "score_change";
};

// 辅助函数 - 构建接口请求参数
const buildRequestParams = () => {
  const {
    time_range,
    asset_ip,
    risk_level,
    change_type,
    score_min,
    score_max,
    department,
    template,
    sort_by,
    sort_order,
  } = filterForm.value;
  const { start_date, end_date, asset_group, operator, has_change, dimension } =
    advancedFilterForm.value;

  // 构建时间范围
  let timeRangeObj: { start_date?: string; end_date?: string } | undefined;
  if (start_date && end_date) {
    // 优先使用高级筛选的日期范围
    timeRangeObj = { start_date, end_date };
  } else if (time_range && time_range !== "custom") {
    // 使用基础筛选的时间范围
    timeRangeObj = convertTimeRange(time_range);
  }

  // 构建筛选条件
  const filters: any = {};

  if (timeRangeObj) {
    filters.time_range = timeRangeObj;
  }

  if (asset_ip) {
    filters.asset_ip = asset_ip;
  }

  if (risk_level) {
    filters.risk_levels = [risk_level];
  }

  if (change_type) {
    filters.change_types = [convertChangeType(change_type)];
  }

  if (score_min !== undefined || score_max !== undefined) {
    filters.score_range = {};
    if (score_min !== undefined) filters.score_range.min = score_min;
    if (score_max !== undefined) filters.score_range.max = score_max;
  }

  if (department) {
    filters.department_name = department;
  }

  // template 可能是字符串，需要转换为 template_id
  // 这里暂时不处理，如果后端需要 template_id，需要根据 template code 查询
  // filters.template_id = template;

  // 高级筛选条件
  if (asset_group) {
    // 如果高级筛选有资产组，可能需要特殊处理
  }

  return {
    page: pagination.currentPage,
    page_size: pagination.pageSize,
    filters: Object.keys(filters).length > 0 ? filters : undefined,
    order_by: convertSortField(sort_by),
    order_direction: sort_order as "asc" | "desc",
  };
};

// 辅助函数 - 构建统计和图表请求参数（只包含filters）
const buildFiltersParams = () => {
  const {
    time_range,
    asset_ip,
    risk_level,
    change_type,
    score_min,
    score_max,
    department,
    template,
  } = filterForm.value;
  const { start_date, end_date, asset_group, operator, has_change, dimension } =
    advancedFilterForm.value;

  // 构建时间范围
  let timeRangeObj: { start_date?: string; end_date?: string } | undefined;
  if (start_date && end_date) {
    // 优先使用高级筛选的日期范围
    timeRangeObj = { start_date, end_date };
  } else if (time_range && time_range !== "custom") {
    // 使用基础筛选的时间范围
    timeRangeObj = convertTimeRange(time_range);
  }

  // 构建筛选条件
  const filters: any = {};

  if (timeRangeObj) {
    filters.time_range = timeRangeObj;
  }

  if (asset_ip) {
    filters.asset_ip = asset_ip;
  }

  if (risk_level) {
    filters.risk_levels = [risk_level];
  }

  if (change_type) {
    filters.change_types = [convertChangeType(change_type)];
  }

  if (score_min !== undefined || score_max !== undefined) {
    filters.score_range = {};
    if (score_min !== undefined) filters.score_range.min = score_min;
    if (score_max !== undefined) filters.score_range.max = score_max;
  }

  if (department) {
    filters.department_name = department;
  }

  return {
    filters: Object.keys(filters).length > 0 ? filters : undefined,
  };
};

// 方法 - 获取统计数据
const fetchStatistics = async () => {
  statsLoading.value = true;
  try {
    const params = buildFiltersParams();
    const { data } = await getHistoryStatistics(params);
    // 映射接口返回的数据到组件需要的格式
    statistics.value = {
      total_records: data.total_records || 0,
      today_records: data.today_count || 0,
      week_records: data.this_week_count || 0,
      avg_score_change: data.average_score_change || 0,
      abnormal_records: data.abnormal_records || 0,
    };
  } catch (error) {
    console.error("获取统计数据失败:", error);
    ElMessage.error("获取统计数据失败");
  } finally {
    statsLoading.value = false;
  }
};

// 方法 - 获取历史列表
const fetchHistoryList = async () => {
  tableLoading.value = true;
  try {
    const params = buildRequestParams();
    const { data } = await getHistoryList(params);
    // 接口返回的数据结构：data.items 而不是 data.list
    historyList.value = data.items || [];
    pagination.total = data.total || 0;
  } catch (error) {
    console.error("获取历史记录失败:", error);
    ElMessage.error("获取历史记录失败");
  } finally {
    tableLoading.value = false;
  }
};

// 方法 - 获取图表数据
// const fetchChartData = async () => {
//   chartLoading.value = true;
//   try {
//     const params = buildFiltersParams();
//     const { data } = await getHistoryChartData(params);
//     chartData.value = data;
//   } catch (error) {
//     console.error("获取图表数据失败:", error);
//     ElMessage.error("获取图表数据失败");
//   } finally {
//     chartLoading.value = false;
//   }
// };

// 事件处理 - 刷新
const handleRefresh = () => {
  fetchStatistics();
  fetchHistoryList();
  // fetchChartData();
};

// 事件处理 - 导出
const handleExport = async () => {
  try {
    await ElMessageBox.confirm(
      "确定要导出历史记录数据吗？导出可能需要一些时间，请耐心等待。",
      "确认导出",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "info",
      }
    );

    ElMessage.info("正在生成Excel文件，请稍候...");

    // 构建导出参数
    const params = buildRequestParams();
    const exportParams = {
      format: "excel" as const,
      filters: params.filters,
      order_by: params.order_by,
      order_direction: params.order_direction,
    };

    const blob = await exportHistoryData(exportParams);

    // 生成文件名
    const timestamp = new Date()
      .toISOString()
      .replace(/[-:]/g, "")
      .split(".")[0];
    const filename = `评分历史记录_${timestamp}.xlsx`;

    // 创建下载链接
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);

    ElMessage.success("导出成功！");
  } catch (error: any) {
    if (error !== "cancel") {
      console.error("导出失败:", error);
      ElMessage.error("导出失败，请稍后重试");
    }
  }
};

// 事件处理 - 搜索
const handleSearch = (formData) => {
  filterForm.value = { ...filterForm.value, ...formData };
  pagination.currentPage = 1;
  // fetchStatistics();
  fetchHistoryList();
  // fetchChartData();
};

// 事件处理 - 分页
const handlePageChange = (page) => {
  pagination.currentPage = page;
  fetchHistoryList();
};

const handleSizeChange = (size) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchHistoryList();
};

// 事件处理 - 查看详情
const handleViewDetail = (id) => {
  currentDetailId.value = id;
  showDetailDialog.value = true;
};

// 事件处理 - 对比
const handleCompare = (row) => {
  currentCompareIp.value = row.asset_ip;
  currentCompareIds.value = [row.id]; // 可以扩展为多选对比
  showCompareDialog.value = true;
};

// 事件处理 - 高级筛选
const handleAdvancedFilterConfirm = (formData) => {
  advancedFilterForm.value = formData;
  showAdvancedFilterDialog.value = false;
  pagination.currentPage = 1;
  fetchStatistics();
  fetchHistoryList();
  // fetchChartData();
};

const handleAdvancedFilterReset = () => {
  advancedFilterForm.value = {
    start_date: "",
    end_date: "",
    asset_group: "",
    operator: "",
    has_change: "",
    dimension: "",
  };
};

// 页面加载时初始化
onMounted(() => {
  fetchStatistics();
  fetchHistoryList();
  // fetchChartData();
});

// 监听高级筛选开关
watch(showAdvancedFilter, (val) => {
  if (val) {
    showAdvancedFilterDialog.value = true;
  }
});
</script>

<style scoped lang="scss">
.history-list-container {
  padding: 16px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 16px;

  .page-title {
    font-size: 18px;
    font-weight: 600;
    color: #1d2129;
    display: flex;
    align-items: center;
    margin: 0;
  }

  .header-actions {
    display: flex;
    gap: 8px;
  }
}

.risk-indicator {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  display: inline-block;
  margin-right: 4px;
}

.monospace-text {
  font-family: monospace;
  background-color: #f5f5f5;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 13px;
}
</style>
